<template>
  <div class="order-archive">
    <h1>订单归档列表</h1>
    <div class="table-container">
      <!-- 查询表单 -->
      <el-card class="search-card">
        <el-form :model="queryForm" inline @submit.prevent="debounceQuery">
          <el-form-item label="工单ID">
            <el-input 
              v-model="queryForm.id" 
              placeholder="请输入工单ID" 
              clearable 
              @keyup.enter="debounceQuery"
              @input="debounceQuery"
            ></el-input>
          </el-form-item>
          <el-form-item label="工单标题">
            <el-input 
              v-model="queryForm.title" 
              placeholder="请输入工单标题" 
              clearable 
              @keyup.enter="debounceQuery"
              @input="debounceQuery"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系人">
            <el-input 
              v-model="queryForm.name" 
              placeholder="请输入联系人" 
              clearable 
              @keyup.enter="debounceQuery"
              @input="debounceQuery"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchWorkOrderList" :loading="loading">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 刷新按钮和批量操作 -->
      <div style="margin: 15px 0; display: flex; justify-content: space-between;">
        <div>
          <el-button type="primary" @click="fetchWorkOrderList" :loading="loading">
            {{ loading ? '加载中...' : '刷新' }}
          </el-button>
          <el-button 
            type="success" 
            @click="exportSelectedOrders"
            :disabled="selectedOrders.length === 0"
          >
            导出选中订单 ({{ selectedOrders.length }})
          </el-button>
          <el-button 
            type="warning" 
            @click="exportAllOrders"
          >
            导出全部订单
          </el-button>
        </div>
      </div>

      <!-- 工单表格 -->
      <el-table 
        :data="workOrderList" 
        style="width: 100%" 
        border 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="工单ID" width="80" />
        <el-table-column prop="title" label="工单标题" width="150" />
        <el-table-column prop="name" label="联系人" width="100" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="address" label="地址" width="200" />
        <el-table-column prop="des" label="描述" width="200" />
        <el-table-column prop="status" label="工单状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="payStatus" label="支付状态" width="100">
          <template #default="scope">
            <el-tag :type="getPayStatusType(scope.row.payStatus)">
              {{ getPayStatusText(scope.row.payStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="工单类型" width="100">
          <template #default="scope">
            {{ getTypeText(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="productId" label="商品ID" width="100" />
        <el-table-column prop="dispatcherName" label="调度员" width="120" />
        <el-table-column prop="employeeName" label="接单员" width="120" />
        <el-table-column prop="pic" label="图片" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="handleViewDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; justify-content: center;"
      />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog title="编辑工单" v-model="editFormVisible" width="600px">
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px">
        <el-form-item label="工单ID">
          <el-input v-model="editForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="工单标题" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="工单描述" prop="des">
          <el-input v-model="editForm.des" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address"></el-input>
        </el-form-item>
        <el-form-item label="支付状态" prop="payStatus">
          <el-select v-model="editForm.payStatus" placeholder="请选择支付状态">
            <el-option label="未支付" :value="0"></el-option>
            <el-option label="已支付" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择工单状态">
            <el-option label="待分配" :value="0"></el-option>
            <el-option label="处理中" :value="1"></el-option>
            <el-option label="已完成" :value="2"></el-option>
            <el-option label="已取消" :value="3"></el-option>
            <el-option label="已评价" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单类型" prop="type">
          <el-select v-model="editForm.type" placeholder="请选择工单类型">
            <el-option label="普通" :value="0"></el-option>
            <el-option label="紧急" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getWorkOrderListAPI, updateOrderAPI } from '@/apis/order'
import { getUserInfoAPI } from '@/apis/sys'
import { formatDate } from '@/utils/date'

export default {
  name: 'OrderArchive',
  data() {
    return {
      workOrderList: [],
      loading: false,
      editFormVisible: false,
      editForm: {
        id: undefined,
        title: '',
        des: '',
        name: '',
        phone: '',
        address: '',
        payStatus: 0,
        status: 4, // 默认为已评价状态
        type: 0
      },
      // 添加查询表单数据
      queryForm: {
        id: '',
        title: '',
        name: ''
      },
      // 添加防抖定时器
      queryTimer: null,
      // 分页数据
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 表单验证规则
      rules: {
        title: [
          { required: true, message: '请输入工单标题', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
        ]
      },
      // 选中的订单
      selectedOrders: [],
      // 添加用户信息缓存
      userInfoCache: new Map()
    }
  },
  mounted() {
    this.fetchWorkOrderList()
  },
  methods: {
    async fetchWorkOrderList() {
      this.loading = true
      try {
        const res = await getWorkOrderListAPI()
        if (res.code === 0) {
          // 只显示状态为4的工单（已评价）
          let filteredData = res.data.filter(item => item.status === 4)
          
          // 根据查询条件过滤数据
          if (this.queryForm.id) {
            filteredData = filteredData.filter(item => 
              item.id && item.id.toString().includes(this.queryForm.id)
            )
          }
          
          if (this.queryForm.title) {
            filteredData = filteredData.filter(item => 
              item.title && item.title.includes(this.queryForm.title)
            )
          }
          
          if (this.queryForm.name) {
            filteredData = filteredData.filter(item => 
              item.name && item.name.includes(this.queryForm.name)
            )
          }
          
          // 更新分页总数
          this.pagination.total = filteredData.length
          
          // 实现前端分页
          const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
          const end = start + this.pagination.pageSize
          const pagedData = filteredData.slice(start, end)
          
          // 显示过滤后的数据
          this.workOrderList = await Promise.all(pagedData.map(async item => {
            // 获取调度员和员工的用户名
            const dispatcherName = await this.getUserName(item.dispatcherId);
            const employeeName = await this.getUserName(item.employeeId);
            
            return {
              id: item.id,
              title: item.title || '无标题',
              des: item.des || '无描述',
              name: item.name || '无联系人',
              phone: item.phone || '无联系电话',
              address: item.address || '无地址',
              payStatus: item.payStatus !== undefined ? item.payStatus : 0,
              status: item.status !== undefined ? item.status : 0,
              pic: item.pic || '',
              productId: item.productId || '',
              dispatcherId: item.dispatcherId || '',
              employeeId: item.employeeId || '',
              dispatcherName: dispatcherName || '未知调度员',
              employeeName: employeeName || '未知员工',
              type: item.type !== undefined ? item.type : 0,
              createTime: item.createTime || new Date().toISOString(),
              updateTime: item.updateTime || new Date().toISOString()
            }
          }))
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '获取工单列表失败'
          })
        }
      } catch (error) {
        this.$message({
          type: 'error',
          message: '获取工单列表失败: ' + (error.msg || error.message || '未知错误')
        })
        console.error('获取工单列表失败:', error)
      } finally {
        this.loading = false
      }
    },
    
    // 获取用户名称的方法
    async getUserName(userId) {
      // 如果用户ID为空，直接返回空字符串
      if (!userId) {
        return ''
      }
      
      // 先从缓存中查找
      if (this.userInfoCache.has(userId)) {
        return this.userInfoCache.get(userId)
      }
      
      try {
        const res = await getUserInfoAPI(userId)
        if (res.code === 0 && res.data) {
          const userName = res.data.user?.userName || res.data.user?.name || `用户${userId}`
          // 缓存用户信息
          this.userInfoCache.set(userId, userName)
          return userName
        }
      } catch (error) {
        console.error(`获取用户${userId}信息失败:`, error)
      }
      
      // 如果获取失败，返回默认值
      return `用户${userId}`
    },
    
    // 添加防抖查询功能
    debounceQuery() {
      // 清除之前的定时器
      if (this.queryTimer) {
        clearTimeout(this.queryTimer)
      }
      
      // 设置新的定时器
      this.queryTimer = setTimeout(() => {
        this.pagination.currentPage = 1
        this.fetchWorkOrderList()
      }, 300)
    },
    
    // 添加重置查询功能
    resetQuery() {
      this.queryForm = {
        id: '',
        title: '',
        name: ''
      }
      this.pagination.currentPage = 1
      // 清空缓存
      this.userInfoCache.clear()
      this.fetchWorkOrderList()
    },
    
    // 处理分页大小变化
    handleSizeChange(newSize) {
      this.pagination.pageSize = newSize
      this.pagination.currentPage = 1
      this.fetchWorkOrderList()
    },
    
    // 处理当前页变化
    handleCurrentChange(newPage) {
      this.pagination.currentPage = newPage
      this.fetchWorkOrderList()
    },
    
    getStatusType(status) {
      switch (status) {
        case 0:
          return '' // 待分配
        case 1:
          return 'warning' // 处理中
        case 2:
          return 'success' // 已完成
        case 3:
          return 'danger' // 已取消
        case 4:
          return 'primary' // 已评价
        default:
          return 'info'
      }
    },
    
    getStatusText(status) {
      switch (status) {
        case 0:
          return '待分配'
        case 1:
          return '处理中'
        case 2:
          return '已完成'
        case 3:
          return '已取消'
        case 4:
          return '已评价'
        default:
          return '未知状态'
      }
    },
    
    getPayStatusType(payStatus) {
      switch (payStatus) {
        case 1:
          return 'success'
        default:
          return 'info'
      }
    },
    
    getPayStatusText(payStatus) {
      switch (payStatus) {
        case 1:
          return '已支付'
        default:
          return '未支付'
      }
    },
    
    getTypeText(type) {
      switch (type) {
        case 0:
          return '普通'
        case 1:
          return '紧急'
        default:
          return '未知类型'
      }
    },
    
    // 查看详情
    handleViewDetail(row) {
      this.$router.push({
        name: 'OrderDetail',
        query: {
          id: row.id
        }
      })
    },
    
    showEditForm(row) {
      this.editForm = { ...row }
      this.editFormVisible = true
    },
    
    // 处理编辑表单提交
    handleEdit() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          try {
            const res = await updateOrderAPI(this.editForm)
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: '更新工单成功!'
              })
              this.editFormVisible = false
              // 重新获取列表数据
              this.fetchWorkOrderList()
            } else {
              this.$message({
                type: 'error',
                message: res.msg || '更新工单失败'
              })
            }
          } catch (error) {
            // 检查是否是Promise.reject返回的业务异常
            if (error && error.msg) {
              this.$message({
                type: 'error',
                message: '更新工单失败: ' + error.msg
              })
            } else {
              this.$message({
                type: 'error',
                message: '更新工单失败: ' + (error.message || '未知错误')
              })
            }
            console.error('更新工单失败:', error)
          }
        } else {
          console.log('表单验证失败!')
          return false
        }
      })
    },
    
    formatDate(date) {
      return formatDate(date)
    },
    
    // 处理选中项变化
    handleSelectionChange(selection) {
      this.selectedOrders = selection
    },
    
    // 导出选中的订单
    exportSelectedOrders() {
      if (this.selectedOrders.length === 0) {
        this.$message({
          type: 'warning',
          message: '请至少选择一个订单进行导出'
        })
        return
      }
      
      this.exportOrders(this.selectedOrders, '选中订单');
    },
    
    // 导出所有订单
    exportAllOrders() {
      this.exportOrders(this.workOrderList, '全部订单');
    },
    
    // 导出订单的通用方法
    exportOrders(orders, typeText) {
      // 创建CSV内容
      let csvContent = '\uFEFF' // 添加BOM以支持中文
      
      // 添加表头
      csvContent += '工单ID,工单标题,描述,联系人,联系电话,地址,支付状态,工单状态,工单类型,商品ID,调度员,接单员,图片,创建时间,更新时间\n'
      
      // 添加数据行
      orders.forEach(order => {
        const payStatusText = this.getPayStatusText(order.payStatus)
        const statusText = this.getStatusText(order.status)
        const typeText = this.getTypeText(order.type)
        const createTime = this.formatDate(order.createTime)
        const updateTime = this.formatDate(order.updateTime)
        
        // 转义特殊字符并添加到CSV
        csvContent += `"${order.id}","${order.title}","${order.des}","${order.name}","${order.phone}","${order.address}",`
        csvContent += `"${payStatusText}","${statusText}","${typeText}","${order.productId}","${order.dispatcherName}","${order.employeeName}","${order.pic}","${createTime}","${updateTime}"\n`
      })
      
      // 创建并下载文件
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      
      link.setAttribute('href', url)
      link.setAttribute('download', `订单归档_${typeText}_${new Date().toISOString().slice(0, 10)}.csv`)
      link.style.visibility = 'hidden'
      
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      this.$message({
        type: 'success',
        message: `成功导出 ${orders.length} 个${typeText}`
      })
    }
  }
}
</script>

<style scoped>
.order-archive {
  padding: 20px;
  background-color: #f5f5f5;
}

.order-archive h1 {
  margin-top: 0;
  color: #2c3e50;
}

.table-container {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 4px;
}

.search-card {
  margin-bottom: 15px;
  border-radius: 4px;
}

.search-card :deep(.el-card__body) {
  padding: 15px;
}

.dialog-footer {
  text-align: right;
}
</style>